package com.yj.springbootstudy.mulThread.imooc.juctools;

import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceTest {

    // 代表待拍的车牌
    private static CarLicenseTag carLicenseTag = new CarLicenseTag(80000);
    // 创建一个 AtomicReference 对象，对车牌对象做原子引用封装
    private static AtomicReference<CarLicenseTag> carLicenseTagAtomicReference = new AtomicReference<>(carLicenseTag);

    public static void main(String[] args) {
        // 定义5个客户进行竞拍
        for (int i = 1; i <= 5; i++) {
            AuctionCustomer carAuctionCustomer = new AuctionCustomer(carLicenseTagAtomicReference, carLicenseTag, i);
            // 开始竞拍
            new Thread(carAuctionCustomer).start();
        }
    }
}

/**
 * 车牌
 */
class CarLicenseTag {
    // 每张车牌牌号事先是固定的
    private String licenseTagNo = "沪X66666";
    // 车牌的最新拍卖价格
    private double price = 80000.00;

    public CarLicenseTag(double price) {
        this.price += price;
    }

    public String toString() {
        return "CarLicenseTag{ licenseTagNo='" + licenseTagNo + ", price=" + price + '}';
    }
}


class AuctionCustomer implements Runnable {
    private AtomicReference<CarLicenseTag> carLicenseTagReference;
    private CarLicenseTag carLicenseTag;
    private String customerNo;

    public AuctionCustomer(AtomicReference<CarLicenseTag> carLicenseTagReference, CarLicenseTag carLicenseTag, int customerNo) {
        this.carLicenseTagReference = carLicenseTagReference;
        this.carLicenseTag = carLicenseTag;
        this.customerNo = "第" + customerNo + "位客户";
    }

    public void run() {
        // 客户竞拍行为 (模拟竞拍思考准备时间4秒钟)
        try {
            Thread.sleep(new Random().nextInt(4000));
        } catch (Exception e) {
        }

        // 举牌更新最新的竞拍价格
        // 此处做原子引用更新
        boolean bool = carLicenseTagReference.compareAndSet(carLicenseTag,new CarLicenseTag(new Random().nextInt(1000)));
        System.out.println("第" + customerNo + "位客户竞拍" + bool + " 当前的竞拍信息" + carLicenseTagReference.get().toString());
    }
}
